package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/12 17:24
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
 */
public class Title122 {

    /**
     * 可以多次购买
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 0; i < prices.length; i++) {
            int min = i;
            while (i + 1 < prices.length && prices[i] < prices[i + 1]) {
                i++;
            }
            profit += prices[i] - prices[min];
        }
        return profit;
    }

    /**
     * dp[i][0]：第i天持有股票所得的现金 (买）
     * dp[i][1]：第i天不持有股票所得的现金 （卖）
     * 递推公式：
     * dp[i][0]：dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i])  不买、买
     * dp[i][1]：dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i]) 不卖、卖
     *
     * @param prices
     * @return
     */
    public int maxProfit1(int[] prices) {
        int[][] dp = new int[prices.length][2];
        //初始化
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            //当天不买、买
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
            //当天不卖、卖
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[prices.length - 1][1];
    }

    public int maxProfit2(int[] prices) {
        int[][] dp = new int[2][2];
        //初始化
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            //当天不买、买
            dp[i % 2][0] = Math.max(dp[(i - 1)%2][0], dp[(i - 1)%2][1] - prices[i]);
            //当天不卖、卖
            dp[i%2][1] = Math.max(dp[(i - 1)%2][1], dp[(i - 1)%2][0] + prices[i]);
        }
        return dp[(prices.length - 1) % 2][1];
    }

    public static void main(String[] args) {

    }
}
